//
//  SeckillAreaViewController.m
//  CPICApp
//
//  Created by lizhiwei on 13-3-11.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "SeckillAreaViewController.h"
#import "RCAlertViewUtil.h"
#import "SeckillConfirmViewController.h"
#import "AppDelegate.h"
#import "NSString+SBJson.h"
#import "Config.h"
#import "SeckillDetailViewController.h"
#import "Config.h"
#import "UIImageView+WebCache.h"
#import "OperationLogView.h"
#import "SeckillResultQueryViewController.h"
#import "IFServiceEvaluation.h"

@interface SeckillAreaViewController ()

@end

@implementation SeckillAreaViewController
@synthesize SeckillAreaTable;
@synthesize ListTitle;
@synthesize ListContent;
@synthesize ListImage;
@synthesize ListPrice;
@synthesize ListSeckillPrice;
@synthesize SeckillBtn;
@synthesize ListSeckillBtnTitle;
@synthesize strflag;
@synthesize progress;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"秒杀专区";
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"]) 
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"秒杀专区");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"秒杀专区");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"秒杀专区");
        
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }

    UIButton * CallOutBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [CallOutBtn2 setImage:[UIImage imageNamed:@"SeckillHistory.png"] forState:UIControlStateNormal];
    CallOutBtn2.frame = CGRectMake(260, 10, 109/2, 57/2);
    [CallOutBtn2 addTarget:self action:@selector(ClickSecKillQryBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:CallOutBtn2];
    
    SeckillAreaTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, self.view.frame.size.height-44)];
    SeckillAreaTable.dataSource = self;
    SeckillAreaTable.delegate = self;
    [self.view addSubview:SeckillAreaTable];
    [SeckillAreaTable release];
    
    
    ListContent = [[NSMutableArray alloc] init];
	[ListContent addObjectsFromArray:[NSArray arrayWithObjects:@"秒杀将于23时11分20秒后结束", @"秒杀将于01时11分20秒后开始", @"秒杀将于01时11分20秒后开始", nil]];
    
    ListTitle = [[NSMutableArray alloc]init];
    [ListTitle addObjectsFromArray:[NSArray arrayWithObjects:@"道路救援服务",@"自驾游意外险",@"代驾服务一次", nil]];
    
    ListImage = [[NSMutableArray alloc]init];
    [ListImage addObjectsFromArray:[NSArray arrayWithObjects:@"SecKill_1",@"SecKill_2",@"SecKill_3", nil]];
    
    ListPrice = [[NSMutableArray alloc]init];
    [ListPrice addObjectsFromArray:[NSArray arrayWithObjects:@"原价:80",@"原价:80",@"原价:80", nil]];
    
    ListSeckillPrice = [[NSMutableArray alloc]init];
    [ListSeckillPrice addObjectsFromArray:[NSArray arrayWithObjects:@"30.00",@"30.00",@"30.00", nil]];
    
    ListSeckillBtnTitle = [[NSMutableArray alloc]init];
    [ListSeckillBtnTitle addObjectsFromArray:[NSArray arrayWithObjects:@"立即秒杀",@"秒杀开始",@"秒杀开始", nil]];
    
    IpageNo=1;
    arrSeckillList=[[NSMutableArray alloc]init];
    
    if (_refreshHeaderView == nil)
    {
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.SeckillAreaTable.bounds.size.height, self.view.frame.size.width, self.SeckillAreaTable.bounds.size.height)];
		view.delegate = self;
		[self.SeckillAreaTable addSubview:view];
		_refreshHeaderView = view;
		[view release];
    }
    //  update the last update date
	[_refreshHeaderView refreshLastUpdatedDate];
    [self setSeckillListRequest];
    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bSeckillArea=FALSE;
    
    [self setEvaluationRequest];
}

-(void) ClickCallOutBtn
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if (myDelegate.bSeckillArea==FALSE) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        if ([strFlag isEqualToString:@"0"])
        {
            [self IFServiceEvaluation];
            strFlag = @"1";
        }
        else
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

-(void)setEvaluationRequest
{
    NSLog(@"==================");
    NSString *serviceid =@"50401";
    NSString *servicename =@"秒杀专区";
    IFServiceEvaluation *ifserviceevaluation =[[IFServiceEvaluation alloc]initView:serviceid withserviceName:servicename];
    [ifserviceevaluation setIfServiceEvaluationRequest];
    [ifserviceevaluation setHidden:YES];
    [self.view addSubview:ifserviceevaluation];
    [ifserviceevaluation release];
}
-(void) IFServiceEvaluation
{
    NSString *serviceid =@"50401";
    NSString *servicename =@"秒杀专区";
    NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
    if ([myDefaults stringForKey:serviceid]) {
        NSString *strEvaluate=[myDefaults stringForKey:serviceid];
        if ([strEvaluate isEqualToString:@"1"]) {
            AddServiceEvaluationViewController *serviceevluation = [[AddServiceEvaluationViewController alloc]initView:serviceid withserviceName:servicename];
            [[AppDelegate app].unc pushViewController:serviceevluation animated:YES];
            [serviceevluation release];
        }
        else
        {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
    else
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}


-(void) ClickSecKillQryBtn
{
    SeckillResultQueryViewController *SeckillResultQueryView = [[SeckillResultQueryViewController alloc]init];
    [[AppDelegate app].unc pushViewController:SeckillResultQueryView animated:YES];
    [SeckillResultQueryView release];
}

#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arrSeckillList count];
}

- (CGFloat)tableView:(UITableView *)atableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * kCellID = @"cellID";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellID] autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        //设置选中某行的风格颜色
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        cell.selectionStyle = UITableViewCellEditingStyleNone;
        cell.backgroundColor = [UIColor colorWithRed:239.0f/255.0f green:239.0f/255.0f blue:239.0f/255.0f alpha:1.0f];
        
        UIView *view = [[UIView alloc] initWithFrame:cell.frame];
        
        /*UIImageView * cellimage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)];
         cellimage.image=[UIImage imageNamed:@"SecKill_1.png"];
         [view addSubview:cellimage];
         [cellimage release];*/
        
        if((indexPath.row)%3==0)
        {
            UIImageView * listimage = [[UIImageView alloc]init];
            [listimage setImage:[UIImage imageNamed:[self.ListImage objectAtIndex:0]]];
            [listimage setFrame:CGRectMake(3, 10, listimage.image.size.width/2, listimage.image.size.height/2)];
            [view addSubview:listimage];
            [listimage release];
        }
        else  if((indexPath.row)%3==1)
        {
            UIImageView * listimage = [[UIImageView alloc]init];
            [listimage setImage:[UIImage imageNamed:[self.ListImage objectAtIndex:1]]];
            [listimage setFrame:CGRectMake(3, 10, listimage.image.size.width/2, listimage.image.size.height/2)];
            [view addSubview:listimage];
            [listimage release];
        }
        else  if((indexPath.row)%3==2)
        {
            UIImageView * listimage = [[UIImageView alloc]init];
            [listimage setImage:[UIImage imageNamed:[self.ListImage objectAtIndex:2]]];
            [listimage setFrame:CGRectMake(3, 10, listimage.image.size.width/2, listimage.image.size.height/2)];
            [view addSubview:listimage];
            [listimage release];
        }
        
        //Flag = indexPath.row;
        commodityName = [arrSeckillList objectAtIndex:indexPath.row];
        /*------------------------开始时间比对*/
        
        NSString *BeginTime = [[NSString alloc] initWithFormat:@"%@",[commodityName objectForKey:@"beginTime"]];
        
        NSDateFormatter *format=[[NSDateFormatter alloc] init];
        [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *fromdate=[format dateFromString:BeginTime];
        NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
        NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
        NSDate *fromDate = [fromdate  dateByAddingTimeInterval: frominterval];
        [format release];
        
        NSDate *date = [NSDate date];
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSInteger interval = [zone secondsFromGMTForDate: date];
        NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
        
        NSTimeInterval secondsBetweenDates= [localeDate timeIntervalSinceDate:fromDate];
        NSLog(@"开始时间比对%lf",secondsBetweenDates);
        /*------------------------开始时间比对*/
        
        /*------------------------结束时间比对*/
        
        NSString *EndTime = [[NSString alloc] initWithFormat:@"%@",[commodityName objectForKey:@"endTime"]];
        
        NSDateFormatter *formatdate=[[NSDateFormatter alloc] init];
        [formatdate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *Fromdate=[formatdate dateFromString:EndTime];
        NSTimeZone *Fromzone = [NSTimeZone systemTimeZone];
        NSInteger Frominterval = [Fromzone secondsFromGMTForDate: Fromdate];
        NSDate *FromDate = [Fromdate  dateByAddingTimeInterval: Frominterval];
        [formatdate release];
        
        NSDate * Date = [NSDate date];
        NSTimeZone *Zone = [NSTimeZone systemTimeZone];
        NSInteger Interval = [Zone secondsFromGMTForDate: Date];
        NSDate *LocaleDate = [Date  dateByAddingTimeInterval: Interval];
        
        NSTimeInterval SecondsBetweenDates= [LocaleDate timeIntervalSinceDate:FromDate];
        NSLog(@"结束时间比对%lf",SecondsBetweenDates);
        /*------------------------结束时间比对*/
        
        SeckillBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        SeckillBtn.frame = CGRectMake(265, 28, 109/2, 60/2);
        SeckillBtn.tag = indexPath.row;
        
        NSString *strCommodityAmount=[[NSString alloc]initWithFormat:@"%@",[commodityName objectForKey:@"commodityAmount"]];
        NSInteger iCommoodityAmount=strCommodityAmount.intValue;
        if (iCommoodityAmount<=0) {
            UILabel *labelContent = [[UILabel alloc] init];
            [labelContent setText:[[NSString alloc] initWithFormat:@"商品库存数量为空"]];
            [labelContent setFrame:CGRectMake(50, 20, 250, 20)];
            [labelContent setTextColor:[UIColor redColor]];
            [labelContent setFont:[UIFont systemFontOfSize:13.0]];
            [labelContent setBackgroundColor:[UIColor clearColor]];
            [view addSubview:labelContent];
            [labelContent release];
            
            [SeckillBtn setImage:[UIImage imageNamed:@"SecKill_03"]forState:UIControlStateNormal];
            [SeckillBtn addTarget:self action:@selector(EndSeckill:) forControlEvents:UIControlEventTouchUpInside];
            [SeckillBtn setEnabled:NO];
        }
        else
        {
            if (SecondsBetweenDates>0)
            {
                UILabel *labelContent = [[UILabel alloc] init];
                [labelContent setText:[[NSString alloc] initWithFormat:@"秒杀于%@已结束",[commodityName objectForKey:@"endTime"]]];
                [labelContent setFrame:CGRectMake(50, 20, 250, 20)];
                [labelContent setTextColor:[UIColor redColor]];
                [labelContent setFont:[UIFont systemFontOfSize:13.0]];
                [labelContent setBackgroundColor:[UIColor clearColor]];
                [view addSubview:labelContent];
                [labelContent release];
                
                [SeckillBtn setImage:[UIImage imageNamed:@"SecKill_03"]forState:UIControlStateNormal];
                [SeckillBtn addTarget:self action:@selector(EndSeckill:) forControlEvents:UIControlEventTouchUpInside];
                [SeckillBtn setEnabled:NO];
            }
            else if (secondsBetweenDates<0)
            {
                if ([strflag isEqualToString:@"1"])
                {
                    UILabel *labelContent = [[UILabel alloc] init];
                    [labelContent setText:[[NSString alloc] initWithFormat:@"秒杀将于%@后开始",[commodityName objectForKey:@"beginTime"]]];
                    [labelContent setFrame:CGRectMake(50, 20, 250, 20)];
                    [labelContent setTextColor:[UIColor redColor]];
                    [labelContent setFont:[UIFont systemFontOfSize:13.0]];
                    [labelContent setBackgroundColor:[UIColor clearColor]];
                    [view addSubview:labelContent];
                    [labelContent release];
                    
                    [SeckillBtn setImage:[UIImage imageNamed:@"SecKill_02"]forState:UIControlStateNormal];
                    [SeckillBtn setEnabled:NO];
                }
                else
                {
                    UILabel *labelContent = [[UILabel alloc] init];
                    [labelContent setText:[[NSString alloc] initWithFormat:@"秒杀将于%@后开始",[commodityName objectForKey:@"beginTime"]]];
                    [labelContent setFrame:CGRectMake(50, 20, 250, 20)];
                    [labelContent setTextColor:[UIColor redColor]];
                    [labelContent setFont:[UIFont systemFontOfSize:13.0]];
                    [labelContent setBackgroundColor:[UIColor clearColor]];
                    [view addSubview:labelContent];
                    [labelContent release];
                    
                    GLOBAL_TIMEBASE = [[NSString alloc] initWithFormat:@"秒杀将于%@后开始",[commodityName objectForKey:@"beginTime"]];
                    
                    [SeckillBtn setImage:[UIImage imageNamed:@"SecKill_02"]forState:UIControlStateNormal];
                    [SeckillBtn setEnabled:NO];
                    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerSeckill:) userInfo:self.view repeats:YES];
                    
                    [[NSNotificationCenter defaultCenter] addObserver: self
                                                             selector: @selector(SecKill:)
                                                                 name: @"SecKill" object: nil];
                }
                
                
                [SeckillBtn addTarget:self action:@selector(StartSeckill:) forControlEvents:UIControlEventTouchUpInside];
            }
            /*else if(SecondsBetweenDates>0)
             {
             UILabel *labelContent = [[UILabel alloc] init];
             [labelContent setText:[[NSString alloc] initWithFormat:@"秒杀于%@已结束",[commodityName objectForKey:@"endTime"]]];
             [labelContent setFrame:CGRectMake(50, 20, 250, 20)];
             [labelContent setTextColor:[UIColor redColor]];
             [labelContent setFont:[UIFont systemFontOfSize:13.0]];
             [labelContent setBackgroundColor:[UIColor clearColor]];
             [view addSubview:labelContent];
             [labelContent release];
             
             [SeckillBtn setImage:[UIImage imageNamed:@"SecKill_03"]forState:UIControlStateNormal];
             [SeckillBtn addTarget:self action:@selector(EndSeckill) forControlEvents:UIControlEventTouchUpInside];
             [SeckillBtn setEnabled:YES];
             }*/
            else if(secondsBetweenDates>0 && SecondsBetweenDates<0)
            {
                UILabel *labelContent = [[UILabel alloc] init];
                [labelContent setText:[[NSString alloc] initWithFormat:@"秒杀将于%@后结束",[commodityName objectForKey:@"endTime"]]];
                [labelContent setFrame:CGRectMake(50, 20, 250, 20)];
                [labelContent setTextColor:[UIColor redColor]];
                [labelContent setFont:[UIFont systemFontOfSize:13.0]];
                [labelContent setBackgroundColor:[UIColor clearColor]];
                [view addSubview:labelContent];
                [labelContent release];
                
                [SeckillBtn setImage:[UIImage imageNamed:@"SecKill_01"]forState:UIControlStateNormal];
                [SeckillBtn addTarget:self action:@selector(AtOnceSeckill:) forControlEvents:UIControlEventTouchUpInside];
                [SeckillBtn setTitle:@"秒杀开始" forState:UIControlStateNormal];
            }
        }
        
        UILabel *labelTitle= [[UILabel alloc] init];
        [labelTitle setText:[[NSString alloc] initWithFormat:@"%@",[commodityName objectForKey:@"commodityName"]]];
        [labelTitle setFrame:CGRectMake(50, 0, 200, 30)];
        [labelTitle setFont:[UIFont boldSystemFontOfSize:14.0]];
        [labelTitle setBackgroundColor:[UIColor clearColor]];
        
        UILabel *labelPrice = [[UILabel alloc] init];
        [labelPrice setText:[[NSString alloc] initWithFormat:@"原价:%@",[commodityName objectForKey:@"originalPrice"]]];
        [labelPrice setFrame:CGRectMake(50, 35, 100, 20)];
        [labelPrice setTextColor:[UIColor redColor]];
        [labelPrice setFont:[UIFont systemFontOfSize:13.0]];
        [labelPrice setBackgroundColor:[UIColor clearColor]];
        
        UILabel *labelSeckillPrice = [[UILabel alloc] init];
        [labelSeckillPrice setText:[[NSString alloc] initWithFormat:@"秒杀价:%@",[commodityName objectForKey:@"secKillPrice"]]];
        [labelSeckillPrice setFrame:CGRectMake(160, 35, 100, 20)];
        [labelSeckillPrice setTextColor:[UIColor redColor]];
        [labelSeckillPrice setFont:[UIFont systemFontOfSize:13.0]];
        [labelSeckillPrice setBackgroundColor:[UIColor clearColor]];
        
        /*if ([[self.ListSeckillBtnTitle objectAtIndex:indexPath.row] isEqualToString:@"立即秒杀"])
        {
            [SeckillBtn addTarget:self action:@selector(AtOnceSeckill) forControlEvents:UIControlEventTouchUpInside];
        }
        else
        {
            if ([strflag isEqualToString:@"1"])
            {
                [SeckillBtn setEnabled:YES];
            }
            else
            {
                [SeckillBtn setEnabled:NO];
                [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerSeckill:) userInfo:self.view repeats:YES];
                
                [[NSNotificationCenter defaultCenter] addObserver: self
                                                         selector: @selector(SecKill:)
                                                             name: @"SecKill"
                                                           object: nil];
            }
            
            
            [SeckillBtn addTarget:self action:@selector(StartSeckill) forControlEvents:UIControlEventTouchUpInside];
        }*/
        
        [view addSubview:SeckillBtn];
        
        [view addSubview:labelTitle];
        [view addSubview:labelPrice];
        [view addSubview:labelSeckillPrice];
        
        [labelTitle release];
        [labelPrice release];
        [labelSeckillPrice release];
        [strCommodityAmount release];
        
        [cell addSubview:view];
        [view release];
	}
    
	return cell;
    
}

-(void) SecKill:(id)sender
{
    strflag = @"1";
    //[self viewDidLoad];
}

-(void) timerSeckill:(NSTimer *)theTimer
{
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *fromdate=[format dateFromString:GLOBAL_TIMEBASE];
    NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
    NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
    NSDate *fromDate = [fromdate  dateByAddingTimeInterval: frominterval];
    [format release];
    
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    
    NSTimeInterval secondsBetweenDates= [fromDate timeIntervalSinceDate:localeDate];
    NSLog(@"=========%lf",secondsBetweenDates);
    if (secondsBetweenDates >= 0)
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"SecKill" object:self];
        [SeckillBtn setTitle:@"立即秒杀" forState:UIControlStateNormal];
        [theTimer invalidate];
    }
}

//立即秒杀
-(void) AtOnceSeckill:(id)sender
{
    //进入秒杀确认页面
    /*NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];*/
    UIButton *button = (UIButton *)sender;
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString * locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"---------------%@",locationString);
    NSString * seckillSuccesstime = locationString;

    commodityName = [arrSeckillList objectAtIndex:button.tag];
    NSLog(@"999999999------%@",commodityName);
    [commodityName setObject:seckillSuccesstime forKey:@"successTime"];
    SeckillConfirmView = [[SeckillConfirmViewController alloc]initView:commodityName];
     SeckillConfirmView.SeckillSuccessTime = seckillSuccesstime;
    [[AppDelegate app].unc pushViewController:SeckillConfirmView animated:YES];
    [SeckillConfirmView release];
}

//开始秒杀
-(void) StartSeckill:(id)sender
{
    //进入秒杀确认页面
    UIButton *button = (UIButton *)sender;
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString * locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"---------------%@",locationString);
    NSString * seckillSuccesstime = locationString;
    
    commodityName = [arrSeckillList objectAtIndex:button.tag];
    NSLog(@"999999999------%@",commodityName);
    [commodityName setObject:seckillSuccesstime forKey:@"successTime"];
     SeckillConfirmView = [[SeckillConfirmViewController alloc]initView:commodityName];
    [[AppDelegate app].unc pushViewController:SeckillConfirmView animated:YES];
    [SeckillConfirmView release];
}

-(void) EndSeckill:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
    NSDate * senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString * locationString=[dateformatter stringFromDate:senddate];
    NSLog(@"---------------%@",locationString);
    NSString * seckillSuccesstime = locationString;
    
    commodityName = [arrSeckillList objectAtIndex:button.tag];
    NSLog(@"999999999------%@",commodityName);
    [commodityName setObject:seckillSuccesstime forKey:@"successTime"];
    SeckillConfirmView = [[SeckillConfirmViewController alloc]initView:commodityName];
    
    [[AppDelegate app].unc pushViewController:SeckillConfirmView animated:YES];
    [SeckillConfirmView release];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *commodityID=[[arrSeckillList objectAtIndex:indexPath.row]valueForKey:@"commodityID"];
    SeckillDetailViewController * seckilldetail = [[SeckillDetailViewController alloc]initView:commodityID];
    [[AppDelegate app].unc pushViewController:seckilldetail animated:YES];
    [seckilldetail setSeckillDetailRequest];
    [seckilldetail release];
}

-(void)setSeckillListRequest//向太保移动平台发送请求报文
{
    NSLog(@"userinfodefault%@",[[NSUserDefaults standardUserDefaults] objectForKey:DICT_USER_INFO]);
    NSDictionary *dictUserInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:DICT_USER_INFO];
    if (dictUserInfo!=nil) {
        if ([dictUserInfo valueForKey:@"UserAccount"]) {
            NSLog(@"%@",[dictUserInfo valueForKey:@"UserAccount"]);
        }
    }
    else
    {
//        [self justShowMessage:@"用户还没登录,请登录系统" title:@"注意"];
//        return;
    }

    NSString * useraccount;
    if ([dictUserInfo valueForKey:@"UserAccount"]) {
        useraccount = [dictUserInfo valueForKey:@"UserAccount"];
    }
    else
    {
        useraccount=@"cpic";
    }
     
//    NSString *strRequestCode=@"RequestCode=50401";
    NSString * PageNo = [[NSString alloc]initWithFormat:@"%d",IpageNo];
    NSString *strRequestData=[NSString stringWithFormat:@"{\"pageNo\":\"%@\",\"total\":\"10\",\"PageSize\":\"10\",\"userAccount\":\"%@\"}",PageNo,useraccount];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestData];
//    NSLog(@"++++++++++++++%@",strUrl);
//    strUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    
//    NSURL *myurl = [NSURL URLWithString:strUrl];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"URL:%@",myurl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"50401" forKey:@"RequestCode"];
    [request setPostValue:strRequestData forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress)
    {
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"加载中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    strFlag=@"0";
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictopinion=[dictResponse objectForKey:@"secKillCommodityInfoList"];
    NSMutableArray *myArrData=[dictopinion objectForKey:@"data"];
    NSLog(@"==========%@",myArrData);
    for (int i=0; i<[myArrData count]; i++) 
    {
        NSMutableDictionary *dictItem=[myArrData objectAtIndex:i];
        [arrSeckillList addObject:dictItem];
    }
    [SeckillAreaTable reloadData];
    
    NSString *Code =@"60601";
    OperationLogView *operationlog =[[OperationLogView alloc]initView:Code withtype:@"1" withserialno:@""];
    [operationlog setOperationLogRequest];
    [operationlog setHidden:YES];
    [self.view addSubview:operationlog];
    [operationlog release];
}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败！" title:@"提示"];
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.SeckillAreaTable];
	
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
    IpageNo=IpageNo+1;
    [self setSeckillListRequest];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}


-(void)dealloc
{
    _refreshHeaderView = nil;
    [super dealloc];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    [SeckillAreaTable release];
    [SeckillBtn release];
    [arrSeckillList release];
    [progress release];
    _refreshHeaderView=nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
